package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.And;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: changgou_parent
 * @Package: com.changgou.service.impl
 * @ClassName: SearchServiceImpl
 * @Author: 孙明田
 * @Description:
 * @Date: 2020/6/19 19:56
 * @Version: 1.0
 */

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //根据查询条件进行数据查询
    @Override
    public Map search(Map<String, String> searchMap) {
        Map<String, Object> resultMap = new HashMap<>();

        //构建查询

        if (searchMap != null) {

            //构建查询条件封装对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //按照关键字进行查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }

            //按照品牌进行过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //根据规格进行过滤查询
            //获取搜索参数searchMap中的所有key
            for (String key : searchMap.keySet()) {
                //value中特殊字符处理
                if (key.startsWith("spec_")) {
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
                }
            }

            //根据价格进行查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))) {
                //0-500 500-1000 1000-1500 3000以上
                //切割价格字符串,获得数组
                String[] prices = searchMap.get("price").split("-");
                //查询
                if (prices.length == 2) {
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            //根据品牌进行分组(聚合)查询
            String skuBrand = "skuBrand";
            //addAggregation()添加聚合
            //terms 分组查询后的列明
            //field 当前操作的分组域
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //根据规格进行分组(聚合)查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //分页查询
            String currentPage = searchMap.get("currentPage");
            String pageSize = searchMap.get("pageSize");
            if (StringUtils.isEmpty(currentPage)) {
                currentPage = "1";
            }

            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //进行查询
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(currentPage) - 1, Integer.parseInt(pageSize)));

            //根据某个字段进行排序
            //"sortField"排序字段  "sortRule"排序方式
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                //进行排序查询 升序
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                } else {
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }

            
            //设置高亮域与高亮样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("name") //设置高亮域
                    .preTags("<span style ='color:red'>") //设置高亮样式的前缀
                    .postTags("</span>"); //设置高亮样式的后缀

            nativeSearchQueryBuilder.withHighlightFields(field);


            nativeSearchQueryBuilder.withQuery(boolQuery);
            //开启查询

            /**
             * 第一个参数：条件查询对象
             * 第二个参数：查询操作实体类
             * 第三个参数：查询结果操作对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //查询结果操作
                    List<T> list = new ArrayList();
                    //获取查询命中结果数据
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        //如果有值，遍历hits
                        for (SearchHit hit : hits) {
                            //将SearchHit转换为skuInfo
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);

                            //获取所有的高亮域
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            //判断是都存在
                            if (highlightFields != null && highlightFields.size() > 0) {
                                //替换数据
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }

                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            //封装最终的返回结果
            //封装分页查询结果
            resultMap.put("currentPage", currentPage);
            //总记录数
            resultMap.put("total", resultInfo.getTotalElements());
            //总页数
            resultMap.put("totalPages", resultInfo.getTotalPages());
            //数据集合
            resultMap.put("rows", resultInfo.getContent());

            //封装品牌的分组结果
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
            List<String> brandList = new ArrayList<String>();
            for (StringTerms.Bucket bucket : brandTerms.getBuckets()) {
                brandList.add(bucket.getKeyAsString());
            }
            resultMap.put("brandList", brandList);

            //封装规格的分组结果
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
            List<String> specList = new ArrayList<String>();

            for (StringTerms.Bucket bucket : specTerms.getBuckets()) {
                specList.add(bucket.getKeyAsString());
            }
            //或者用流运算
            //specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());

            resultMap.put("specList", specList);


            return resultMap;
        }
        return null;
    }
}
